package com.msb.netty.udp.multicast;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    
    private static ChannelGroup clientChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        clientChannels.add(channel);
        
        String sendMsg = "客户[" + channel.remoteAddress() + "]上线\n";
        System.out.print(sendMsg);
        clientChannels.forEach(clientChannel -> {
            if (clientChannel != channel) {
                clientChannel.writeAndFlush(sendMsg);
            } else {
                clientChannel.writeAndFlush("欢迎您上线\n");
            }
        });
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        if (clientChannels.contains(channel)) {
            clientChannels.remove(channel);
            
            String sendMsg = "客户[" + channel.remoteAddress() + "]异常下线\n";
            System.out.print(sendMsg);
            clientChannels.forEach(clientChannel -> clientChannel.writeAndFlush(sendMsg));
        }
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        Channel channel = ctx.channel();
        ByteBuf byteBuf = packet.content();
        String str = byteBuf.toString(CharsetUtil.UTF_8);
        if (str.equals("quit")) {
            clientChannels.remove(channel);
            channel.close();
            System.out.println("客户[" + channel.remoteAddress() + "]下线\n");
        }
        clientChannels.forEach(clientChannel -> {
            if (clientChannel != channel) {
//                clientChannel.writeAndFlush(new DatagramPacket(packet.content(), ));
            }
        });
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        clientChannels.remove(channel);
        
        String msg = cause.getMessage();
        String sendMsg = "客户[" + channel.remoteAddress() + "]异常: " + msg + "\n";
        System.out.print(sendMsg);
        clientChannels.forEach(clientChannel -> clientChannel.writeAndFlush(sendMsg));
    }
}
